﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Synchronization;
using Telerik.Web.UI;

namespace Medianamik.UI.Controls
{
    internal class SubGridColumnTemplate : ITemplate
    {
        private Literal _name;
        public string ColumnName { get; private set; }

        public SubGridColumnTemplate(string columnName)
        {
            ColumnName = columnName;
        }

        public void InstantiateIn(Control container)
        {
            var p = new HtmlGenericControl("p");
            container.Controls.Add(p);

            _name = new Literal {ID = ColumnName};
            p.Controls.Add(_name);
            _name.DataBinding += NameDataBinding;
        }

        void NameDataBinding(object sender, EventArgs e)
        {
            var container = (GridDataItem)_name.NamingContainer;
            var node = ((Record)container.DataItem);

            if(ColumnName.EqualsIgnoreCase("createdon"))
            {
                var createdOn = node.CreatedOn ?? DateTime.Now;
                _name.Text = createdOn.ToString(MedianamikContext
                    .Current.CurrentUICulture.DateTimeFormat);
            }
            else if(ColumnName.EqualsIgnoreCase("createdby"))
            {
                _name.Text = node.CreatedBy;
            }
            else
            {
                _name.Text = node.Properties.First(p => p.NodeTypePropertyName
                    .Equals(ColumnName, StringComparison.OrdinalIgnoreCase)).Value.ToString();
            }
        }
    }
}